package com.shop.cereshop.app.controller.buyer;

import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.page.buyer.blacklist.BuyerBlacklistVO;
import com.shop.cereshop.app.param.buyer.blacklist.AddBlacklistParam;
import com.shop.cereshop.app.param.buyer.blacklist.BatchRemoveBlacklistParam;
import com.shop.cereshop.app.param.buyer.blacklist.QueryBlacklistParam;
import com.shop.cereshop.app.service.buyer.BuyerUserBlacklistService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;

import com.shop.cereshop.commons.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @description: 用户黑名单相关接口
 * @author zdd
 * @date 2025/11/12 16:20
 * @version 1.0
 */
@Api(value = "用户黑名单相关接口", tags = "用户黑名单相关接口")
@RestController
@RequestMapping("/buyer/blacklist")
@Slf4j(topic = "BuyerUserBlacklistController")
@RequiredArgsConstructor
public class BuyerUserBlacklistController {

    private final BuyerUserBlacklistService buyerUserBlacklistService;

    @ApiOperation(value = "获取黑名单列表")
    @GetMapping("/page")
    public Result<PageInfo<BuyerBlacklistVO>> getBlacklistList(QueryBlacklistParam param, HttpServletRequest request) {
        try {
            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            param.setBuyerUserId(buyerUserId);
            return buyerUserBlacklistService.getBlacklistPage(param);
        } catch (Exception e) {
            log.error("获取黑名单列表异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }

    @ApiOperation(value = "添加黑名单")
    @PostMapping("/add")
    public Result<Object> addBlacklist(@RequestBody @Valid AddBlacklistParam param, HttpServletRequest request) {
        try {
            if (param.getBlockedUserId() == null) {
                return Result.failed(CoReturnFormat.PARAM_INVALID, "被拉黑的用户ID不能为空");
            }
            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            // 不能拉黑自己
            if (buyerUserId.equals(param.getBlockedUserId())) {
                return Result.failed(CoReturnFormat.PARAM_INVALID, "不能拉黑自己");
            }
            param.setBuyerUserId(buyerUserId);
            return buyerUserBlacklistService.addBlacklist(param);
        } catch (Exception e) {
            log.error("添加黑名单异常", e);
            return Result.failed(CoReturnFormat.SYS_ERROR, "添加黑名单异常");
        }
    }

    @ApiOperation(value = "移除黑名单")
    @DeleteMapping("/remove/{blockedUserId}")
    public Result<Object> removeBlacklist(@PathVariable Long blockedUserId, HttpServletRequest request) {
        try {
            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            return buyerUserBlacklistService.removeBlacklist(buyerUserId, blockedUserId);
        } catch (Exception e) {
            log.error("移除黑名单异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }

    @ApiOperation(value = "批量移除黑名单")
    @PostMapping("/batch-remove")
    public Result<Object> batchRemoveBlacklist(@RequestBody BatchRemoveBlacklistParam param, HttpServletRequest request) {
        try {
            List<Long> blockedUserIds = param.getBlockedUserIds();
            if (blockedUserIds == null || blockedUserIds.isEmpty()) {
                return Result.failed(CoReturnFormat.PARAM_INVALID, "被拉黑用户ID列表不能为空");
            }
            if (blockedUserIds.size() > 100) {
                return Result.failed(CoReturnFormat.PARAM_INVALID, "单次批量操作最多支持100个用户");
            }

            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            return buyerUserBlacklistService.batchRemoveBlacklist(buyerUserId, blockedUserIds);
        } catch (Exception e) {
            log.error("批量移除黑名单异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }

    @ApiOperation(value = "检查是否在黑名单中")
    @GetMapping("/check")
    public Result<Boolean> checkInBlacklist(@RequestParam Long targetUserId, HttpServletRequest request) {
        try {
            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            boolean inBlacklist = buyerUserBlacklistService.isInBlacklist(buyerUserId, targetUserId);
            return new Result<>(inBlacklist);
        } catch (Exception e) {
            log.error("检查黑名单异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }

    @ApiOperation(value = "获取被哪些用户拉黑了")
    @GetMapping("/blocked-by")
    public Result<List<Long>> getBlockedByUserIds(HttpServletRequest request) {
        try {
            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            List<Long> blockedByUserIds = buyerUserBlacklistService.getBlockedByUserId(buyerUserId);
            return new Result<>(blockedByUserIds);
        } catch (Exception e) {
            log.error("获取被拉黑列表异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }

    @ApiOperation(value = "获取黑名单统计")
    @GetMapping("/stats")
    public Result<Map<String, Object>> getBlacklistStats(HttpServletRequest request) {
        try {
            // 获取当前登录用户
            CereBuyerUser currentUser = (CereBuyerUser) request.getAttribute("user");
            if (currentUser == null) {
                return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
            }
            Long buyerUserId = currentUser.getBuyerUserId();
            Map<String, Object> stats = buyerUserBlacklistService.getBlacklistStats(buyerUserId);
            return new Result<>(stats);
        } catch (Exception e) {
            log.error("获取黑名单统计异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }

    @ApiOperation(value = "手动触发自动解封（管理员用）")
    @PostMapping("/auto-unblock")
    public Result<Object> triggerAutoUnblock() {
        try {
            buyerUserBlacklistService.autoUnblockExpiredBlacklists();
            return new Result<>(CoReturnFormat.SUCCESS);
        } catch (Exception e) {
            log.error("手动触发自动解封异常", e);
            return new Result<>(CoReturnFormat.SYS_ERROR);
        }
    }


}
